package com.example.framework.mvp.mvp.presenter

import android.content.Context
import com.example.framework.mvp.mvp.view.BaseView
import kotlinx.coroutines.*
import java.lang.ref.Reference
import java.lang.ref.WeakReference

/**
 * @name:
 *  BasePresenter
 * @package:
 *  com.example.framework.mvp.mvp.presenter
 * @date:
 *  2023/2/1714:26
 * @author
 *    cmy
 * @description
 *
 */
abstract class BasePresenter<V : BaseView?>(@JvmField protected var mContext: Context) {

    private var mViewRef: Reference<V?>? = null

    private val presenterScope: CoroutineScope by lazy {
        CoroutineScope(Dispatchers.Main + Job())
    }

    /**
     * 运行在IO线程的协程，主要用于数据网络请求
     */
    fun launchIO(block: suspend CoroutineScope.() -> Unit) = presenterScope.launch (Dispatchers.IO){  block() }

    /**
     * 主线程的数据处理
     */
    fun launchUI(block: suspend CoroutineScope.() -> Unit) = presenterScope.launch (Dispatchers.Main){  block() }

    /**
     * 默认格式
     */
    fun launch(block: suspend CoroutineScope.() -> Unit) = presenterScope.launch{  block() }
    /**
     * 关联View
     *
     * @param view view
     */
    fun attachView(view: V) {
        mViewRef = WeakReference(view)
    }

    /**
     * 销毁
     */
    open fun detachView() {
        if (isViewAttached) {
            //取消协程信息
            presenterScope.cancel()
            //取消页面绑定
            mViewRef?.clear()
        }
    }

    /**
     * 获取
     *
     * @return View
     */
    val view: V?
        get() = mViewRef?.get()

    /**
     * 是否已经关联
     *
     * @return 关联状态
     */
    private val isViewAttached: Boolean
        get() = mViewRef?.let { it.get() != null } ?: false



}